var chunkSize = 1 * 1024 * 1024;    //每片大小
// var chunkSize = 512 * 1024;    //每片大小

//文件分片
function sliceFile(file) {
    const chunks = [];
    let start = 0;
    let end;
    while (start < file.size) {
        end = Math.min(start + chunkSize, file.size);
        chunks.push(file.slice(start, end));
        start = end;
    }
    return chunks;
}

function checkFile() {
    var xhr = new XMLHttpRequest();
    // 当上传完成时调用
    xhr.onload = function () {
        if (xhr.status === 200) {
            checkFileRes.innerHTML = '检测文件完整性成功:' + xhr.responseText;
        }
    }
    xhr.onerror = function () {
        checkFileRes.innerHTML = '检测文件完整性失败';
    }
    // 发送请求
    xhr.open('POST', '/checkFile', true);
    let data = new FormData();
    data.append("md5", fileMd5)
    xhr.send(data);
}

function uploadChunk(data,progressBarFill,progressPercent) {
    var xhr = new XMLHttpRequest();
    // 当上传完成时调用
    xhr.onload = function () {
        if (xhr.status === 200) {
            var obj = JSON.parse(JSON.parse(xhr.responseText));
            console.log(obj);
            var width = parseFloat(progressBarFill.style.width || 0, 10);
            if(obj.completed === true) {
                width = 100
            } else {
                var percentComplete = (data.get("chunkSize") / data.get("totalSize")) * 100;
                width += percentComplete;
                width = width.toFixed(2);
                if(width > 100) {
                    width = 100
                }
            }
            updateProgressBar(progressBarFill,progressPercent,width)
        }
    }
    xhr.onerror = function () {
        console.log(xhr.responseText);
    }
    // 发送请求
    xhr.open('POST', '/upload', true);
    xhr.send(data);
 }


 function uploadFileLast(file,fileMd5,progressBarFill,progressPercent) {
    if (!file) return;
    if (!fileMd5) return;


    //获取到文件
    let fileArr = this.sliceFile(file);
    //保存文件名称
    let fileName = file.name;

    fileArr.forEach((e, i) => {
        let chunkFile = new File([e],fileName);
        console.log(chunkFile);
        //创建formdata对象
        let data = new FormData();
        data.append("totalSize", file.size)
        data.append("totalNumber", fileArr.length)
        data.append("chunkSize", chunkFile.size)
        data.append("chunkNumber", i)
        data.append("md5", fileMd5)
        data.append("file", chunkFile);
        uploadChunk(data,progressBarFill,progressPercent);
    })
}

//unuse
function uploadFiles2() {  
    var interval = setInterval(function() {  
        var allComplete = true;  
        const progressItems = document.getElementsByClassName('progress-item');
        console.log("progressItems.length:"+progressItems.length);
        for (var i = 0; i < progressItems.length; i++) {  
            var progressBarFill = progressItems[i].querySelector('.progress-bar-fill');  
            var progressPercent = progressItems[i].querySelector('.progress-percent');  
                
            var width = parseInt(progressBarFill.style.width || 0, 10);  

            if (width < 100) {  
                width += 10; // 模拟进度增加  
                progressBarFill.style.width = width + '%';  
                progressPercent.textContent = width + '%';  
                allComplete = false;  
            }  

            // if (width < 100) {  
            //     fetch("/progress_bar")
            //     .then(response => {
            //         // 确保响应是OK的
            //         if (!response.ok) {
            //         throw new Error('Network response was not ok ' + response.statusText);
            //         }
            //         return response.json(); // 解析JSON数据
            //     })
            //     .then(data => {
            //         // 这里处理获取到的数据
            //         width = parseInt(data)
            //         progressBarFill.style.width = width + '%';  
            //         progressPercent.innerText = width + '%';
    
            //         console.log(data);
            //     })
            //     .catch(error => {
            //         // 处理任何获取数据时的错误
            //         console.error('There has been a problem with your fetch operation:', error);
            //     });
            //     allComplete = false;  
            // }  
        }  
    
        if (allComplete) {  
            clearInterval(intervalId);  
            // 所有文件上传完成后的处理...  
        } 
    }, 100); // 每100毫秒更新一次进度  
}


function uploadFiles() {  
    const progressItems = document.getElementsByClassName('progress-item');
    for (var i = 0; i < progressItems.length; i++) {  
        var progressBarFill = progressItems[i].querySelector('.progress-bar-fill');  
        var progressPercent = progressItems[i].querySelector('.progress-percent');  
        pollProgress(progressBarFill,progressPercent);
    }
}


function pollProgress(progressBarFill,progressPercent) {  
    // 使用setInterval来轮询进度  
    let intervalId = setInterval(function() {  
        fetch('/progress_bar') // 或者使用XMLHttpRequest  
            .then(response => response.json())  
            .then(data => {  
                // 假设后端返回的数据结构为 { percent: 50 }  
                // let percent = data.percent;  
                let percent = parseInt(data)
                updateProgressBar(progressBarFill,progressPercent, percent); // 更新进度条  
  
                // 检查是否完成，如果完成则停止轮询  
                if (percent === 100) {  
                    clearInterval(intervalId);  
                    // 可以添加文件上传完成的逻辑  
                }  
            })  
            .catch(error => {  
                console.error('Error fetching progress:', error);  
                clearInterval(intervalId); // 发生错误时停止轮询  
            });  
    }, 1000); // 每秒轮询一次  
}  


function updateProgressBar(progressBarFill,progressPercent, percent) {  
    progressBarFill.style.width = percent + '%';  
    progressPercent.textContent = percent + '%';  
}  




document.getElementById('files').addEventListener('change', function() {  
    var files = this.files; 
    
    var uploadButton = document.getElementById('uploadButton');  
    var progressContainer = document.getElementById('progressContainer');

     // 清除之前的进度条  
     progressContainer.innerHTML = '';  
      
    if (files.length > 0) {  
        uploadButton.disabled = false; // 如果有文件被选中，启用上传按钮  
         // 为每个文件创建进度条  
         for (var i = 0; i < files.length; i++) {  
            var file = files[i];
            
            var info_str = "文件名: " + file.name + "\r\n文件大小: " + file.size + "\r\nMD5值: ";

            var progressItem = document.createElement('div');  
            progressItem.classList.add('progress-item');  

            var infoDiv = document.createElement('div');  
            infoDiv.classList.add('file-info');  
            infoDiv.innerText = info_str;

            calculateFileMD5(file,infoDiv);
  
            var progressBar = document.createElement('div');  
            progressBar.classList.add('progress-bar');  
  
            var progressBarFill = document.createElement('div');  
            progressBarFill.classList.add('progress-bar-fill');  
            progressBarFill.style.width = '0%'; // 初始化为0%  
  
            var progressPercent = document.createElement('span');  
            progressPercent.classList.add('progress-percent');  
            progressPercent.textContent = '0%';  
  

            progressItem.appendChild(infoDiv);
            progressBar.appendChild(progressBarFill); // 进度条填充  
            progressItem.appendChild(progressBar); // 进度条  
            progressItem.appendChild(progressPercent); // 百分比在进度条之后  

            progressContainer.appendChild(progressItem);  
        }  
    } else {  
        uploadButton.disabled = true; // 如果没有文件被选中，禁用上传按钮  
    }  
});  


function calculateFileMD5(file,infoDiv){
    getFileMd5(file).then((md5) => {
        console.info(md5)
        infoDiv.innerText += md5
        infoDiv.setAttribute("md5", md5);
    })
}

function getFileMd5(file) {
    return new Promise((resolve, reject) => {
        let fileReader = new FileReader()
        fileReader.onload = function (event) {
            let fileMd5 = SparkMD5.ArrayBuffer.hash(event.target.result)
            resolve(fileMd5)
        }
        fileReader.readAsArrayBuffer(file)
    })
}


function uploadFilesNew() {  
    var files = document.getElementById('files').files;
    const progressItems = document.getElementsByClassName('progress-item');
    console.log(files);
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var progressBarFill = progressItems[i].querySelector('.progress-bar-fill');  
        var progressPercent = progressItems[i].querySelector('.progress-percent');  
        var fileMd5 = progressItems[i].querySelector('.file-info').getAttribute('md5');  
        // upload(file,progressBarFill,progressPercent);
        uploadFileLast(file,fileMd5,progressBarFill,progressPercent);
    }
}



function upload(file,progressBarFill,progressPercent) {
    // 创建 XMLHttpRequest 对象
    var xhr = new XMLHttpRequest();

    // 配置上传路径
    var url = '/upload'; // 服务器上传接口
    
    // 新建一个 FormData 对象
    var data = new FormData();
    
    // 添加文件数据
    data.append('file', file); // fileInputElement 是文件输入元素的 ID
    
    // 开始上传
    xhr.open('POST', url, true);
    
    // 监听上传进度
    xhr.upload.onprogress = function(event) {
    if (event.lengthComputable) {
        var percentComplete = (event.loaded / event.total) * 100;
        // 更新进度条或显示进度
        console.log(percentComplete.toFixed(2) + '%');
        updateProgressBar(progressBarFill,progressPercent,percentComplete.toFixed(2));
    }
    };
    
    // 上传完成
    xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('上传成功');
    } else {
        console.log('上传失败');
    }
    };
    
    // 发送请求
    xhr.send(data);

}